package app.qrcode.browser.ykpixabay.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.content.ContextCompat
import app.qrcode.browser.ykpixabay.R

/**
 * Created by YiGo on 2022/4/17.
 */
class EditTextWithClear @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatEditText(context, attrs) {
    private var iconDrawable: Drawable? = null

    init {
        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.EditTextWithClear,
            0,
            0
        ).apply {
            try {
                val iconID = getResourceId(R.styleable.EditTextWithClear_clearIcon, 0)
                if (iconID != 0) {
                    iconDrawable = ContextCompat.getDrawable(context, iconID)
                }
            } finally {
                recycle()
            }
        }

    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        toggleClearIcon()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let { e ->
            iconDrawable?.let {
                if (e.action == MotionEvent.ACTION_UP &&
                    e.x > width - it.intrinsicWidth - 20 &&
                    e.x < width + 20 &&
                    e.y > height / 2 - it.intrinsicHeight / 2 - 20 &&
                    e.y < height / 2 + it.intrinsicHeight / 2 + 20
                ) {
                    text?.clear()
                }
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        toggleClearIcon()
    }

    private fun toggleClearIcon() {
        val icon = if (isFocused && text?.isNotEmpty() == true) iconDrawable else null
        setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, icon, null)
    }
}